﻿using agsXMPP;
using agsXMPP.protocol.client;
using IMDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IMDemo.Views
{
    /// <summary>
    /// UCGroup.xaml 的交互逻辑
    /// </summary>
    public partial class UCGroup : UserControl
    {
        private XmppClientConnection xmppClient = null;

        #region 属性
        private ContactModel currentGroup;

        public ContactModel CurrentGroup
        {
            get
            {
                return this.currentGroup;
            }
        }
        #endregion

        public UCGroup(XmppClientConnection conn)
        {
            InitializeComponent();
            this.xmppClient = conn;
            this.DataContext = this;
        }

        public UCGroup(XmppClientConnection conn, ContactModel model) : this(conn)
        {
            this.currentGroup = model;
            this.InitReceiver();
        }

        private void btnSendMessage_Click(object sender, RoutedEventArgs e)
        {
            this.OnSendMessage(this.currentGroup);
        }

        #region 初始化信息接收者
        private void InitReceiver()
        {
            try
            {
                Presence pres = new Presence();

                Jid to = new Jid(this.currentGroup.ContactJid.ToString());
                to.Resource = Config.LoginUser.Bare;
                pres.To = to;
                this.xmppClient.Send(pres);
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger(this.GetType()).Error(ex);
            }
        }

        void consumer_Listener(MessageModel message)
        {
            this.OnReceivedMessage(message);
        }
        #endregion

        #region 自定义事件
        #region SendMessage
        public delegate void SendMessageHandle(object sender, ContactModel to);

        public event SendMessageHandle SendMessage;

        public void OnSendMessage(ContactModel to)
        {
            if (this.SendMessage != null)
            {
                this.SendMessage(this, to);
            }
        }
        #endregion

        #region ReceivedMessage
        public delegate void ReceivedMessageHandle(object sender, MessageModel message);

        public event ReceivedMessageHandle ReceivedMessage;

        public void OnReceivedMessage(MessageModel message)
        {
            if (this.ReceivedMessage != null)
            {
                this.ReceivedMessage(this, message);
            }
        }
        #endregion
        #endregion
    }
}
